picker
<template>
  <xh-container
    btnText="保存"
    @onSave="handleClickSubmit"
    :title="formData.pickPlanId ? '编辑' : '新增'"
  >
    <view class="container">
      <uni-forms
        ref="form1"
        :rules="rules1"
        :modelValue="formData"
        :label-width="80"
        label-align="right"
      >
        <uni-forms-item required label="领料时间" name="pickDate">
          <uni-datetime-picker
            type="date"
            v-model="formData.pickDate"
            :start="Date.now()"
          />
        </uni-forms-item>
        <uni-forms-item required label="裁片编码" name="cuttingCode">
          <xh-multiple-select
            v-model="formData.cuttingCode"
            placeholder="请选择裁片"
            :localdata="cuttingList"
            :map="{ text: 'cuttingCode', value: 'cuttingCode' }"
            @change="handleChangeCutting"
          />
        </uni-forms-item>
        <uni-forms-item label="产品名称" name="productName">
          <uni-easyinput
            disabled
            v-model="formData.productName"
            placeholder="产品名称"
          />
        </uni-forms-item>
        <uni-forms-item label="领料人" name="pickPerson">
          <xh-data-select
            v-if="isAdmin"
            v-model="formData.pickPerson"
            :localdata="pickPersonList"
            @change="handleSetTotalAmount(item)"
          />
          <uni-easyinput
            v-else
            disabled
            v-model="formData.pickPerson"
            placeholder="领料人"
          />
        </uni-forms-item>
        <uni-forms-item label="可持数量" name="totalAmount">
          <uni-easyinput
            disabled
            v-model="formData.totalAmount"
            placeholder="可持数量"
          />
        </uni-forms-item>
        <uni-forms-item label="需求数量" name="pickAmount">
          <uni-easyinput
            disabled
            v-model="formData.pickAmount"
            placeholder="需求数量"
          />
        </uni-forms-item>
      </uni-forms>
      <uni-section title="新增辅料" type="line">
        <uni-table border stripe emptyText="暂无更多数据">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th align="center" v-for="item in columns" :key="item.title">{{
              item.title
            }}</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in tableData" :key="index">
            <uni-td align="center">{{ item.productName }}</uni-td>
            <uni-td align="center">
              {{ item.unit || "-" }}
            </uni-td>
            <uni-td align="center">{{ item.num || "-" }}</uni-td>
            <uni-td>
              <view class="uni-group">
                <!-- <xh-button size="mini" type="primary"> 修改 </xh-button> -->
                <xh-button
                  size="mini"
                  type="warn"
                  @click="handelClickDel(index)"
                  >删除</xh-button
                >
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <xh-button :borderRadius="0" type="default" @click="handelClickAdd"
          >添加</xh-button
        >
      </uni-section>
      <xh-popup
        title="添加辅料"
        ref="xhPopup"
        @ok="handleClickOk"
        @close="handleClickClose"
      >
        <uni-forms
          ref="form2"
          :modelValue="detailData"
          :label-width="90"
          :rules="rules2"
        >
          <uni-forms-item label="产品名称" name="productName">
            <uni-data-select
              v-model="detailData.productName"
              :localdata="materialbillList"
              @change="handleChangeMaterial"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="单位" name="unit">
            <uni-easyinput
              type="text"
              disabled
              v-model="detailData.unit"
              placeholder="单位"
            />
          </uni-forms-item>
          <uni-forms-item label="辅料数量" name="num">
            <uni-easyinput
              type="number"
              v-model="detailData.num"
              placeholder="请输入辅料数量"
            />
          </uni-forms-item>
        </uni-forms>
      </xh-popup>
    </view>
  </xh-container>
</template>

<script>
import {
  getCuttingList,
  addPickplanbill,
  getAccessories,
  editPickplanbill,
  getPersonAmountList,
} from "@/api/purchase/pickplanbill.js";
import { formatSelectList } from "@/utils/business.js";
import mixins from "../mixins";
import AppStorage from "../../utils/appStorage";
import { Role } from "@/utils/constant";
export default {
  mixins: [mixins],
  data() {
    return {
      formData: {},
      detailData: {},
      tableData: [],
      isAdmin: false,
      columns: [
        {
          title: "绣花辅料",
        },
        {
          title: "单位",
        },
        {
          title: "辅料数量",
        },
        {
          title: "操作",
        },
      ],
      cuttingList: [], // 裁片编码list
      materialbillList: [],
      pickPersonList: [],
      rules1: {
        pickDate: {
          rules: [
            {
              required: true,
              errorMessage: "请选择领料时间",
            },
          ],
        },
        cuttingList: {
          rules: [
            {
              required: true,
              errorMessage: "请选择裁片编码",
            },
          ],
        },
      },
      rules2: {
        productName: {
          rules: [
            {
              required: true,
              errorMessage: "请选择产品",
            },
          ],
        },
      },
    };
  },
  computed: {
    // ...mapGetters(['mobileInboundList', 'productList']),
  },
  created() {
    this.init();
    this.fetchPersonAmountList();
  },
  mounted() {
    this.fetchCuttingList();
  },

  onLoad(options) {
    const { cuttingCode, pickPlanId, ...rest } = options;
    const userInfo = AppStorage.get("userInfo");
    this.formData = {
      ...rest,
      pickPlanId,
      cuttingCode: cuttingCode?.split(","),
      pickPerson: userInfo.nickName,
    };
    this.fetchTableData(pickPlanId);
  },
  methods: {
    init() {
      const userInfo = AppStorage.get("userInfo");
      this.isAdmin = userInfo.roleKeys?.includes(Role.admin);
    },
    handleChangeCutting(list) {
      if (Array.isArray(list)) {
        this.formData.productName = list
          .map((item) => item.productName)
          ?.join(",");
      }
    },
    // 设置totalAmount参数
    handleSetTotalAmount(currentPerson) {
      const person = this.pickPersonList.find(
        (item) =>
          item.productCode === currentPerson.userName ||
          currentPerson.productCode
      );
      if (person) {
        this.formData = {
          ...this.formData,
          totalAmount: person.totalAmount,
        };
      } else {
        console.error("组件addForm，totalAmount为空");
      }
    },
    // 请求领料人数据
    fetchPersonAmountList() {
      getPersonAmountList().then((res) => {
        const { rows } = res;
        this.pickPersonList = formatSelectList(rows, "productName");
        const userInfo = AppStorage.get("userInfo");
        this.handleSetTotalAmount(userInfo);
      });
    },
    fetchTableData(id) {
      getAccessories(id).then((res) => {
        const { data } = res;
        this.tableData = data || [];
      });
    },
    handleChangeMaterial(val) {
      const mItem = this.materialbillList.find((item) => item.value === val);
      const { unit } = mItem;
      this.detailData.unit = unit;
    },
    fetchCuttingList() {
      const { pickPlanId, pickPerson, totalAmount } = this.formData;
      let params = {};
      if (pickPlanId) {
        params = {
          pickPlanId,
          pickPerson,
          totalAmount,
        };
      }
      getCuttingList(params).then((res) => {
        const { rows } = res;
        this.cuttingList = formatSelectList(rows, "cuttingCode");
      });
    },
    // 关闭 添加明细弹窗
    handleClickClose() {
      this.$refs.form2.clearValidate();
      this.detailData = {};
    },
    // 删除
    handelClickDel(index) {
      this.tableData.splice(index, 1);
    },
    // 提交
    handleClickSubmit() {
      this.$refs.form1
        .validate()
        .then(() => {
          const { cuttingCode, ...rest } = this.formData;
          const params = {
            ...rest,
            workshop: "1",
            accessoriesList: this.tableData,
            cuttingCode: cuttingCode.join(","),
          };
          const { pickPlanId } = this.formData;
          if (pickPlanId) {
            editPickplanbill({
              pickPlanId,
              ...params,
            }).then(() => {
              this.handleSuccess();
            });
          } else {
            addPickplanbill(params).then(() => {
              this.handleSuccess();
            });
          }
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    handleSuccess() {
      this.$modal.msgSuccess("操作成功！");
      this.clearData();
      this.$nav.navigateBack();
    },
    clearData() {
      this.tableData = [];
      this.detailData = {};
      this.formData = {};
    },
    handleClickOk() {
      this.$refs.form2
        .validate()
        .then(() => {
          this.tableData.push(this.detailData);
          this.detailData = {};
          this.$refs.xhPopup.close();
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    // 添加
    handelClickAdd() {
      this.$refs.xhPopup.open("top");
    },
  },
  watch: {
    "formData.cuttingCode": {
      // immediate: true, // 如果需要在组件实例化时立即触发，设置immediate为true
      handler(newVal) {
        let pickAmount = 0;
        if (newVal) {
          pickAmount = newVal.length;
        }
        this.formData.pickAmount = pickAmount;
      },
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
}

.popup-title {
  line-height: 45px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  height: 45px;
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
}

.popup-footer {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;
    }
  }
}

.form-content {
  padding: 10px;
}

.btn-wrapper {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;

      &::after {
        border-left: none;
      }
    }

    &::after {
      border-radius: 0;
    }
  }
}
</style>
